
#include "iot_pwm.h"
#include "iot_errno.h"

#include "door.h"

/* sg90 pwm */
#define SG90_PWM_PORT EPWMDEV_PWM0_M1
int sg90_init(int pwm_pin)
{
    uint8_t ret = IOT_FAILURE;

    ret = IoTPwmInit((enum EnumPwmDev)pwm_pin);
    if (ret != IOT_SUCCESS)
    {
        printf("%s, %s, %d: PWM Init fail\n", __FILE__, __func__, __LINE__);
    }

    return ret;
}

/**
 * @brief sg90 释放
 *
 */
int sg90_deinit(int pwm_pin)
{
    return IoTPwmDeinit((enum EnumPwmDev)pwm_pin);
}

/**
 * @brief sg90 设置角度
 *
 * @param angel sg90_angel_e 角度
 */
int sg90_set_angel(int pwm_pin, sg90_angel_e angel)
{
    const uint32_t freq = 50;
    static sg90_angel_e last_angel = SG90_ANGEL_0;
    uint16_t duty = 0;
    int ret = 0;

    printf("sg90_set_angle. angle = %d\n", angel);
    if (last_angel != angel)
    {
        switch (angel)
        {
        case SG90_ANGEL_0:
            duty = (uint16_t)(0.06 * (double)freq);
            break;
        case SG90_ANGEL_45:
            duty = (uint16_t)(0.10 * (double)freq);
            break;
        case SG90_ANGEL_90:
            duty = (uint16_t)(0.15 * (double)freq);
            break;
        case SG90_ANGEL_135:
            duty = (uint16_t)(0.20 * (double)freq);
            break;
        case SG90_ANGEL_180:
            duty = (uint16_t)(0.25 * (double)freq);
            break;
        default:
            return -1;
        }

        ret = IoTPwmStart(pwm_pin, duty, freq);
        last_angel = angel;
    }
    return ret;
}
